package com.hzcx.app.simplechat.chat.adapter;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.*;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.util.MultiTypeDelegate;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMFileMessageBody;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMLocationMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.DateUtils;
import com.hyphenate.util.EMLog;
import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.chat.bean.ChatCustomServiceMenuBean;
import com.hzcx.app.simplechat.chat.bean.ChatNoticeBean;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.chat.interfaces.OnChatMessageListener;
import com.hzcx.app.simplechat.chat.ui.BubbleImageView;
import com.hzcx.app.simplechat.chat.util.EaseChatRowVoicePlayer;
import com.hzcx.app.simplechat.model.PublicModel;
import com.hzcx.app.simplechat.ui.chat.ChatGroupSettingActivity;
import com.hzcx.app.simplechat.ui.chat.bean.ChatCustomNoticeBean;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.group.bean.GroupSettingBean;
import com.hzcx.app.simplechat.ui.group.bean.MembersBean;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.util.ClickableSpanTextView;
import com.hzcx.app.simplechat.util.LinkifySpannableUtils;
import com.hzcx.app.simplechat.util.TextHttpUtil;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.dp.DpUtils;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.view.AutoWebView;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.litepal.crud.callback.FindCallback;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息列表
 */
public class ChatMessageAdapter extends BaseQuickAdapter<EMMessage, BaseViewHolder> {

    private static final int TYPE_DEFAULT = 0;
    private static final int TYPE_SEND_TEXT = 1;
    private static final int TYPE_RECEIVE_TEXT = 2;
    private static final int TYPE_SEND_IMAGE = 3;
    private static final int TYPE_RECEIVE_IMAGE = 4;
    private static final int TYPE_SEND_VOICE = 5;
    private static final int TYPE_RECEIVE_VOICE = 6;
    private static final int TYPE_SEND_LOCATION = 7;
    private static final int TYPE_RECEIVE_LOCATION = 8;
    private static final int TYPE_SEND_CUSTOM_SHARE = 9;
    private static final int TYPE_RECEIVE_CUSTOM_SHARE = 10;
    private static final int TYPE_RECALL = 11;
    private static final int TYPE_BLACK = 12;
    private static final int TYPE_DELETE = 13;
    private static final int TYPE_CUSTOM_ASSISTANT = 14;
    private static final int TYPE_CUSTOM_NOTICE = 15;
    private static final int TYPE_CUSTOM_IMAGE_SEND = 16;
    private static final int TYPE_CUSTOM_IMAGE_RECEIVE = 17;

    private static final int SEND_TEXT = R.layout.rv_item_chat_message_txt_send;
    private static final int RECEIVE_TEXT = R.layout.rv_item_chat_message_txt_receive;
    private static final int SEND_IMAGE = R.layout.rv_item_chat_message_img_send;
    private static final int RECEIVE_IMAGE = R.layout.rv_item_chat_message_img_recieive;
    private static final int SEND_VOICE = R.layout.rv_item_chat_message_voice_send;
    private static final int RECEIVE_VOICE = R.layout.rv_item_chat_message_voice_receive;
    private static final int SEND_LOCATION = R.layout.rv_item_chat_message_location_send;
    private static final int RECEIVE_LOCATION = R.layout.rv_item_chat_message_location_receive;
    private static final int SEND_CUSTOM_SHARE = R.layout.rv_item_chat_message_share_user_send;
    private static final int RECEIVE_CUSTOM_SHARE = R.layout.rv_item_chat_message_share_user_receive;
    private static final int RECALL = R.layout.rv_item_chat_message_recall;
    private static final int BLACK = R.layout.rv_item_chat_message_black;
    private static final int DELETE = R.layout.rv_item_chat_message_delete;
    private static final int CUSTOM_ASSISTANT = R.layout.rv_item_chat_message_custom_assistant_receive;
    private static final int CUSTOM_NOTICE = R.layout.rv_item_chat_message_custom_notice;
    private static final int CUSTOM_IMAGE_SEND = R.layout.rv_item_chat_message_img_send;
    private static final int CUSTOM_IMAGE_RECEIVE = R.layout.rv_item_chat_message_img_recieive;
    private static final int DEFAULT = R.layout.rv_item_chat_message_default;

    private EaseChatRowVoicePlayer voicePlayer;
    private AnimationDrawable voiceAnimation;
    private OnChatMessageListener messageListener;
    private HxUserInfoBean hxUserInfoBean;
    private boolean isSelectMore = false;
    private boolean isChecked = false;
    private List<Integer> checkBoxList;

    Map<String, MembersBean> userInfoGroupMap = new HashMap<>();
    /**
     * 群组设置保存信息
     */
    GroupSettingBean groupSettingBean;

    public ChatMessageAdapter(@Nullable List<EMMessage> data) {
        super(data);
        setMultiTypeDelegate(new MultiTypeDelegate<EMMessage>() {
            @Override
            protected int getItemType(EMMessage message) {
                if (message.getType() == EMMessage.Type.TXT) {
                    String msg_text = getExtMsg(message);
                    if (msg_text == null) {
                        return message.direct() == EMMessage.Direct.SEND ? TYPE_SEND_TEXT : TYPE_RECEIVE_TEXT;
                    } else if (msg_text.isEmpty()) {
                        return TYPE_BLACK;
                    } else {
                        return TYPE_BLACK;
                    }
//                    try {
//                        boolean to_all = message.getBooleanAttribute("to_all");
//                        return TYPE_BLACK;
//                    } catch (Exception e) {
//                        return message.direct() == EMMessage.Direct.SEND ? TYPE_SEND_TEXT : TYPE_RECEIVE_TEXT;
//                    }
                } else if (message.getType() == EMMessage.Type.IMAGE) {
                    return message.direct() == EMMessage.Direct.SEND ? TYPE_SEND_IMAGE : TYPE_RECEIVE_IMAGE;
                } else if (message.getType() == EMMessage.Type.VIDEO) {
                    return message.direct() == EMMessage.Direct.SEND ? TYPE_SEND_IMAGE : TYPE_RECEIVE_IMAGE;
                }else if (message.getType() == EMMessage.Type.VOICE) {
                    return message.direct() == EMMessage.Direct.SEND ? TYPE_SEND_VOICE : TYPE_RECEIVE_VOICE;
                } else if (message.getType() == EMMessage.Type.LOCATION) {
                    return message.direct() == EMMessage.Direct.SEND ? TYPE_SEND_LOCATION : TYPE_RECEIVE_LOCATION;
                } else if (message.getType() == EMMessage.Type.CUSTOM) {
                    EMCustomMessageBody customBody = (EMCustomMessageBody) message.getBody();
                    String event = customBody.event();
                    if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_SHARE)) {
                        return message.direct() == EMMessage.Direct.SEND ? TYPE_SEND_CUSTOM_SHARE : TYPE_RECEIVE_CUSTOM_SHARE;
                    } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_RECALL)) {
                        return TYPE_RECALL;
                    } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_BLACK)) {
                        return TYPE_BLACK;
                    } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_DELETE)) {
                        return TYPE_DELETE;
                    } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_ASSISTANT)) {
                        return TYPE_CUSTOM_ASSISTANT;
                    } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_NOTICE)) {
                        return TYPE_CUSTOM_NOTICE;
                    } else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)||customBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)) {
                        return message.direct() == EMMessage.Direct.SEND ? TYPE_CUSTOM_IMAGE_SEND : TYPE_CUSTOM_IMAGE_RECEIVE;
                    }
                }
                return TYPE_DEFAULT;
            }
        });

        getMultiTypeDelegate().registerItemType(TYPE_SEND_TEXT, SEND_TEXT)
                .registerItemType(TYPE_RECEIVE_TEXT, RECEIVE_TEXT)
                .registerItemType(TYPE_SEND_IMAGE, SEND_IMAGE)
                .registerItemType(TYPE_RECEIVE_IMAGE, RECEIVE_IMAGE)
                .registerItemType(TYPE_SEND_VOICE, SEND_VOICE)
                .registerItemType(TYPE_RECEIVE_VOICE, RECEIVE_VOICE)
                .registerItemType(TYPE_DEFAULT, DEFAULT)
                .registerItemType(TYPE_SEND_LOCATION, SEND_LOCATION)
                .registerItemType(TYPE_RECEIVE_LOCATION, RECEIVE_LOCATION)
                .registerItemType(TYPE_SEND_CUSTOM_SHARE, SEND_CUSTOM_SHARE)
                .registerItemType(TYPE_RECEIVE_CUSTOM_SHARE, RECEIVE_CUSTOM_SHARE)
                .registerItemType(TYPE_RECALL, RECALL)
                .registerItemType(TYPE_DELETE, DELETE)
                .registerItemType(TYPE_CUSTOM_ASSISTANT, CUSTOM_ASSISTANT)
                .registerItemType(TYPE_CUSTOM_NOTICE, CUSTOM_NOTICE)
                .registerItemType(TYPE_CUSTOM_IMAGE_SEND, CUSTOM_IMAGE_SEND)
                .registerItemType(TYPE_CUSTOM_IMAGE_RECEIVE, CUSTOM_IMAGE_RECEIVE)
                .registerItemType(TYPE_BLACK, BLACK);

        voicePlayer = EaseChatRowVoicePlayer.getInstance(MyApplication.getContext());
    }

    public void updateMembers(Map<String, MembersBean> userInfoGroupMap) {
        this.userInfoGroupMap = userInfoGroupMap;
//        if (this.userInfoGroupMap == null) {
//            this.userInfoGroupMap = userInfoGroupMap;
//        }
    }

    @Override
    protected void convert(BaseViewHolder helper, EMMessage item) {

        TextView tvDate = helper.getView(R.id.tv_date);
        if (tvDate != null) {
            if (helper.getAdapterPosition() == 0) {
                // 第0个表示肯定要展示时间
                tvDate.setVisibility(View.VISIBLE);
                tvDate.setText(DateUtils.getTimestampString(new Date(item.getMsgTime())));
            } else {
                EMMessage prevMessage = mData.get(helper.getAdapterPosition() - 1);
                if (prevMessage != null && DateUtils.isCloseEnough(item.getMsgTime(), prevMessage.getMsgTime())) {
                    tvDate.setVisibility(View.GONE);
                } else {
                    tvDate.setText(DateUtils.getTimestampString(new Date(item.getMsgTime())));
                    tvDate.setVisibility(View.VISIBLE);
                }
            }
        }

        // 处理消息中提示语展示逻辑
        if (item.getType() == EMMessage.Type.TXT) { // 文本消息
            String msg_text = getExtMsg(item);
            if (msg_text == null) {
            } else if (msg_text.isEmpty()) {
                helper.setGone(R.id.tv_black_content, false);
                return;
            } else {
                helper.setText(R.id.tv_black_content, msg_text);
                return;
            }
        }

        // 设置是否是选择更多模式
        if (helper.getView(R.id.iv_check_box) != null) {
            ImageView ivCheckBox = helper.getView(R.id.iv_check_box);
            if (isSelectMore) {
                ivCheckBox.setVisibility(View.VISIBLE);
            } else {
                ivCheckBox.setVisibility(View.GONE);
            }
            if (checkBoxList == null || checkBoxList.size() <= 0) {
                ivCheckBox.setImageResource(R.mipmap.ic_icon_check_normal);
            } else {
                boolean isChecked = false;
                for (int i = 0; i < checkBoxList.size(); i++) {
                    if (checkBoxList.get(i) == helper.getAdapterPosition()) {
                        isChecked = true;
                        break;
                    }
                }
                if (isChecked) {
                    ivCheckBox.setImageResource(R.mipmap.ic_icon_check_select);
                } else {
                    ivCheckBox.setImageResource(R.mipmap.ic_icon_check_normal);
                }
            }
        }

        // 设置消息已读回执
        try {
            EMClient.getInstance().chatManager().ackMessageRead(item.getFrom(), item.getMsgId());
        } catch (HyphenateException e) {
            e.printStackTrace();
        }

        // 会员才有已读功能
        if (UserInfoUtil.getUserIsVip()) {
            // 设置已读未读状态
            if (helper.getView(R.id.iv_read) != null) {
                if (item.isAcked()) {
                    helper.setVisible(R.id.iv_read, true);
                } else {
                    helper.setVisible(R.id.iv_read, false);
                }
            }
        } else {
            if (helper.getView(R.id.iv_read) != null) {
                helper.setVisible(R.id.iv_read, false);
            }
        }

        // 设置通用的字段，头像，昵称等
        if (item.direct() == EMMessage.Direct.SEND) {
            // 自己，设置自己的头像，昵称
            if (helper.getView(R.id.iv_head) != null) {
                try {
                    GlideUtils.loadImg(mContext, UserInfoUtil.getUserHead(), helper.getView(R.id.iv_head));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 设置消息发送状态
            if (item.status() == EMMessage.Status.CREATE || item.status() == EMMessage.Status.INPROGRESS) {
                if (helper.getView(R.id.loading_view) != null) {
                    helper.setVisible(R.id.loading_view, true);
                }
                if (helper.getView(R.id.iv_send_fail) != null) {
                    helper.setVisible(R.id.iv_send_fail, false);
                }
            } else if (item.status() == EMMessage.Status.FAIL) {
                if (helper.getView(R.id.loading_view) != null) {
                    helper.setVisible(R.id.loading_view, false);
                }
                if (helper.getView(R.id.iv_send_fail) != null) {
                    helper.setVisible(R.id.iv_send_fail, true);
                }
            } else {
                if (helper.getView(R.id.loading_view) != null) {
                    helper.setVisible(R.id.loading_view, false);
                }
                if (helper.getView(R.id.iv_send_fail) != null) {
                    helper.setVisible(R.id.iv_send_fail, false);
                }
            }
        } else {
            // 对方,设置对方的头像，昵称等
            try {
                if (item.getChatType() == EMMessage.ChatType.Chat) { // 单聊
                    if (hxUserInfoBean != null) {
                        GlideUtils.loadImg(mContext, hxUserInfoBean.getAvatar(), helper.getView(R.id.iv_head));
                    }
                } else if (item.getChatType() == EMMessage.ChatType.GroupChat) { // 群聊
                    String hxusername = item.getFrom();
                    String groud_id = item.getTo();

//                    groupSettingBean = LitePal.where("group_id=? and myUserId=?", groud_id, UserInfoUtil.getUserId() + "").findFirst(GroupSettingBean.class);
                    LitePal.where("group_id=? and myUserId=?", groud_id, UserInfoUtil.getUserId() + "").findFirstAsync(GroupSettingBean.class).listen(groupSettingBean -> {
                        this.groupSettingBean = groupSettingBean;
                        LitePal.where("hxusername=? and myUserId=?", hxusername, UserInfoUtil.getUserId() + "").findFirstAsync(HxUserInfoBean.class).listen(hxUserInfoBean -> {
//                        helper.setVisible(R.id.tv_nick_name_bg, true);
                            if (hxUserInfoBean == null) {
                                PublicModel.getUserInfoByHx(mContext, hxusername, new BaseObserver<HxUserInfoBean>() {
                                    @Override
                                    protected void onSuccess(HxUserInfoBean data) {
                                        data.setHxusername(hxusername);
                                        data.setMyUserId(UserInfoUtil.getUserId());
                                        data.save();
                                        if (hxUserInfoBean!=null&&!TextUtils.isEmpty(hxUserInfoBean.getAvatar())){
                                            String avatar = hxUserInfoBean.getAvatar();
                                            GlideUtils.loadImg(mContext, avatar, helper.getView(R.id.iv_head));
                                        }
                                        if (groupSettingBean != null && groupSettingBean.isGroupShowNickName()) {
                                            MembersBean bean = userInfoGroupMap.get(hxusername);
                                            String getGroup_member_nickname = bean == null ? null : bean.getGroup_member_nickname();
                                            if (EmptyUtils.isNotEmpty(getGroup_member_nickname)) {
                                                if (helper.getView(R.id.tv_nick_name)!=null) {
                                                    helper.setText(R.id.tv_nick_name, getGroup_member_nickname);
                                                    helper.setVisible(R.id.tv_nick_name_bg,true);
                                                }
                                            } else if (EmptyUtils.isNotEmpty(data.getRemarks_name())) {
                                                if (helper.getView(R.id.tv_nick_name)!=null) {
                                                    helper.setText(R.id.tv_nick_name, data.getRemarks_name());
                                                    helper.setVisible(R.id.tv_nick_name_bg,true);
                                                }
                                            } else if (EmptyUtils.isNotEmpty(data.getNickname())) {
                                                if (helper.getView(R.id.tv_nick_name)!=null) {
                                                    helper.setText(R.id.tv_nick_name, data.getNickname());
                                                    helper.setVisible(R.id.tv_nick_name_bg,true);
                                                }
                                            } else {
                                                if (helper.getView(R.id.tv_nick_name_bg)!=null) {
                                                    helper.setGone(R.id.tv_nick_name_bg, false);
                                                }
                                            }
                                        } else {
                                            if (helper.getView(R.id.tv_nick_name_bg)!=null) {
                                                helper.setGone(R.id.tv_nick_name_bg, false);
                                            }
                                        }
                                    }
                                });
                            } else {
                                String avatar = hxUserInfoBean.getAvatar();
                                if (avatar != null&&helper.getView(R.id.iv_head)!=null) {
                                    GlideUtils.loadImg(mContext, avatar, helper.getView(R.id.iv_head));
                                }

                                Log.e("hxUserInfoBean.getNickname()", "convert: " + hxUserInfoBean.getNickname());
                                if (groupSettingBean != null && groupSettingBean.isGroupShowNickName()) {
                                    MembersBean bean = userInfoGroupMap.get(hxusername);
                                    String getGroup_member_nickname = bean == null ? null : bean.getGroup_member_nickname();
                                    if (EmptyUtils.isNotEmpty(getGroup_member_nickname)) {
                                        if (helper.getView(R.id.tv_nick_name)!=null) {
                                            helper.setText(R.id.tv_nick_name, getGroup_member_nickname);
                                            helper.setVisible(R.id.tv_nick_name_bg,true);
                                        }
                                    } else if (EmptyUtils.isNotEmpty(hxUserInfoBean.getRemarks_name())) {
                                        if (helper.getView(R.id.tv_nick_name)!=null) {
                                            helper.setText(R.id.tv_nick_name, hxUserInfoBean.getRemarks_name());
                                            helper.setVisible(R.id.tv_nick_name_bg,true);
                                        }
                                    } else if (EmptyUtils.isNotEmpty(hxUserInfoBean.getNickname())) {
                                        if (helper.getView(R.id.tv_nick_name)!=null) {
                                            helper.setText(R.id.tv_nick_name, hxUserInfoBean.getNickname());
                                            helper.setVisible(R.id.tv_nick_name_bg,true);
                                        }
                                    } else {
                                        if (helper.getView(R.id.tv_nick_name_bg)!=null) {
                                            helper.setGone(R.id.tv_nick_name_bg, false);
                                        }
                                    }
                                } else {
                                    if (helper.getView(R.id.tv_nick_name_bg)!=null) {
                                        helper.setGone(R.id.tv_nick_name_bg, false);
                                    }
                                }
                            }
                        });

                    });


                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (item.getType() == EMMessage.Type.TXT) { // 文本消息
            EMTextMessageBody txtBody = (EMTextMessageBody) item.getBody();
            ClickableSpanTextView tvContent = helper.getView(R.id.tv_content);
            tvContent.setText(TextHttpUtil.getInstance(mContext).identifyUrl(txtBody.getMessage()));
//            helper.setText(R.id.tv_content, txtBody.getMessage());
//            LinkifySpannableUtils.getInstance().setSpan(mContext, helper.getView(R.id.tv_content));
            tvContent.setOnLongClickListener(view -> {
                if (messageListener != null) {
//                    LinkifySpannableUtilSs.getInstance().setLongClick(true);
                    TextHttpUtil.getInstance(mContext).setLongClick(true);
                    messageListener.onMsgLongClick(item, helper.getView(R.id.rl_item_msg_bg), helper.getAdapterPosition());
                }
                return true;
            });
            LinkifySpannableUtils.getInstance().setOnCallPhoneListener(phone -> {
                if (messageListener != null) {
                    messageListener.callPhoneOnClick(phone);
                }
            });
        } else if (item.getType() == EMMessage.Type.IMAGE) { // 图片消息
            EMImageMessageBody imgBody = (EMImageMessageBody) item.getBody();
            if (item.direct() == EMMessage.Direct.SEND) {
                try {
                    File file = new File(imgBody.getLocalUri().getPath());
                    if (file.exists()) {
                        GlideUtils.loadChatImage(mContext, imgBody.getLocalUri().getPath(), helper.getView(R.id.bivPic));
                    } else {
                        String uri = imgBody.getRemoteUrl();
                        GlideUtils.loadChatImage(mContext, uri, helper.getView(R.id.bivPic));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                String uri = imgBody.getRemoteUrl();
                if (uri != null) {
                    //                LogUtils.i("远程图片地址：" + uri);
                    GlideUtils.loadChatImage(mContext, uri, helper.getView(R.id.bivPic));
                }
            }
            View picView = helper.getView(R.id.bivPic);
            if (picView != null) {
                picView.setOnLongClickListener(view -> {
                    if (messageListener != null) {
                        messageListener.onMsgLongClick(item, helper.getView(R.id.bivPic), helper.getAdapterPosition());
                    }
                    return true;
                });
            }
        } else if (item.getType() == EMMessage.Type.VOICE) { // 语音消息
            EMVoiceMessageBody voiceBody = (EMVoiceMessageBody) item.getBody();
            helper.setText(R.id.tv_time, voiceBody.getLength() + "\"");
            if (item.direct() == EMMessage.Direct.RECEIVE) {

                if (voiceBody.downloadStatus() == EMFileMessageBody.EMDownloadStatus.DOWNLOADING ||
                        voiceBody.downloadStatus() == EMFileMessageBody.EMDownloadStatus.PENDING) {
                    if (EMClient.getInstance().getOptions().getAutodownloadThumbnail()) {
                        helper.setVisible(R.id.loading_view, true);
                    } else {
                        helper.setVisible(R.id.loading_view, false);
                    }
                } else {
                    helper.setVisible(R.id.loading_view, false);
                }
            }

            // 设置长按事件
            helper.getView(R.id.rl_voice_bg).setOnLongClickListener(view -> {
                if (messageListener != null) {
                    messageListener.onMsgLongClick(item, helper.getView(R.id.rl_voice_bg), helper.getAdapterPosition());
                }
                return true;
            });

            // 播放语音
            helper.getView(R.id.rl_voice_bg).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isSelectMore) {
                        return;
                    }
                    if (voicePlayer.isPlaying()) {
                        // Stop the voice play first, no matter the playing voice item is this or others.
                        voicePlayer.stop();
                        // Stop the voice play animation.
                        stopVoicePlayAnimation(item, helper.getView(R.id.iv_voice));

                        // If the playing voice item is this item, only need stop play.
                        String playingId = voicePlayer.getCurrentPlayingId();
                        if (item.getMsgId().equals(playingId)) {
                            return;
                        }
                    } else {
                        if (item.direct() == EMMessage.Direct.SEND) {
                            // Play the voice
                            String localPath = ((EMVoiceMessageBody) item.getBody()).getLocalUrl();
                            File file = new File(localPath);
                            if (file.exists() && file.isFile()) {
                                playVoice(item, helper.getView(R.id.iv_voice));
                                // Start the voice play animation.
                                startVoicePlayAnimation(item, helper.getView(R.id.iv_voice));
                            } else {
                                ToastUtils.show("语音已失效");
                            }
                        } else {
                            if (item.status() == EMMessage.Status.SUCCESS) {
                                if (EMClient.getInstance().getOptions().getAutodownloadThumbnail()) {
                                    play(item, helper.getView(R.id.iv_voice));
                                }
                            } else if (item.status() == EMMessage.Status.INPROGRESS) {
                                ToastUtils.show("正在下载语音，稍后点击");
                            } else if (item.status() == EMMessage.Status.FAIL) {
                                ToastUtils.show("正在下载语音，稍后点击");
                            }
                        }
                    }
                }
            });
        } else if (item.getType() == EMMessage.Type.LOCATION) {  // 位置消息
            try {
                EMLocationMessageBody body = (EMLocationMessageBody) item.getBody();
                helper.setText(R.id.tv_title, body.getAddress());
                helper.setText(R.id.tv_address, item.getStringAttribute(ChatConstant.EXTRA_LOCATION_ADDRESS));

                String location = body.getLongitude() + "," + body.getLatitude();

                LogUtils.d("location:" + location);

                AutoWebView webViewMap = helper.getView(R.id.web_view_map);
                WebSettings settings = webViewMap.getSettings();
                settings.setUseWideViewPort(true);
                settings.setLoadWithOverviewMode(true);
                webViewMap.loadUrl("http://restapi.amap.com/v3/staticmap?location=" + location + "&zoom=15&size=325*150&markers=mid,,A:" + location + "&" +
                        "key=f31cc2d825b490157356cb8159ce7650");

                // 设置长按事件
                helper.getView(R.id.ll_map_view).setOnLongClickListener(view -> {
                    if (messageListener != null) {
                        messageListener.onMsgLongClick(item, helper.getView(R.id.ll_map_view), helper.getAdapterPosition());
                    }
                    return true;
                });
            } catch (Exception e) {
                e.printStackTrace();
                helper.setText(R.id.tv_title, "未知位置消息");
            }
        } else if (item.getType() == EMMessage.Type.CUSTOM) { // 自定义消息
            EMCustomMessageBody customBody = (EMCustomMessageBody) item.getBody();
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_SHARE)) {
                // 分享个人名片消息
                try {
                    GlideUtils.loadImgAsCircle(mContext, item.getStringAttribute(ChatConstant.EXTRA_SHARE_HEAD), helper.getView(R.id.iv_share_head));
                    helper.setText(R.id.tv_share_name, item.getStringAttribute(ChatConstant.EXTRA_SHARE_NICKNAME));
                    helper.setText(R.id.tv_share_number, mContext.getResources().getString(R.string.app_name) + "号:" + item.getStringAttribute(ChatConstant.EXTRA_SHARE_NUMBERID));

                    // 设置长按消息
                    helper.getView(R.id.cons_share_user).setOnLongClickListener(view -> {
                        if (messageListener != null) {
                            messageListener.onMsgLongClick(item, helper.getView(R.id.cons_share_user), helper.getAdapterPosition());
                        }
                        return true;
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_RECALL)) {
                // 撤回消息
                if (item.direct() == EMMessage.Direct.SEND) {
                    helper.setText(R.id.tv_recall_content, "您撤回了一条消息");
                } else {
                    helper.setText(R.id.tv_recall_content, "对方撤回了一条消息");
                }
            }
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_BLACK)) {
                // 黑名单消息
                helper.setText(R.id.tv_black_content, "消息已发出，但被对方拒收了");
            }
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_DELETE)) {
                // 对方已删除
                String str = "<font color='#FFFFFF'>对方开启了朋友验证，请先发送验证请求，对方通过后才能聊天，</font><font color='#22D7CFD'>发送好友验证</font>";
                helper.setText(R.id.tv_delete_content, Html.fromHtml(str));
                helper.getView(R.id.tv_delete_content).setOnClickListener(view -> {
                    if (isSelectMore) {
                        return;
                    }
                    if (messageListener == null) {
                        return;
                    }
                    try {
                        int userId = item.getIntAttribute(ChatConstant.EXTRA_RECEIVE_USER_ID);
                        messageListener.onUserHeadClick(userId, false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_ASSISTANT)) {
                // 官方菜单消息
                try {
                    String msg = item.getStringAttribute(ChatConstant.EXTRA_CUSTOM_ASSISTANT);
                    LogUtils.d("msg:" + msg);
                    List<ChatCustomServiceMenuBean> list = new Gson().fromJson(msg, new TypeToken<List<ChatCustomServiceMenuBean>>() {
                    }.getType());
                    ChatCustomServiceMenuAdapter menuAdapter = new ChatCustomServiceMenuAdapter(list);
                    RecyclerView rvCustomServiceMenu = helper.getView(R.id.rv_custom_service_menu);
                    rvCustomServiceMenu.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
                    rvCustomServiceMenu.setAdapter(menuAdapter);
                    menuAdapter.setOnItemClickListener((adapter, view, position) -> {
                        if (isSelectMore) {
                            return;
                        }
                        if (messageListener != null) {
                            messageListener.assistantOnClick(list.get(position).getReply_id());
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_NOTICE)) {
                // 官方通知
                try {
                    String data = item.getStringAttribute("notice_data");
                    LogUtils.d("data:" + data);
                    ChatCustomNoticeBean bean = new Gson().fromJson(data, ChatCustomNoticeBean.class);
                    helper.setText(R.id.tv_notice_title, bean.getNotice_title());
                    helper.setText(R.id.tv_notice_date, bean.getNotice_date());
                    helper.setText(R.id.tv_notice_content, bean.getNotice_content());
                    helper.setText(R.id.tv_notice_prompt, bean.getNotice_prompt());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)) { // 自定义图片消息
                try {
                    helper.getView(R.id.iv_video).setVisibility(View.GONE);
                    String path = item.getStringAttribute(ChatConstant.EXTRA_IMAGE_PATH);
                    String localPath = item.getStringAttribute(ChatConstant.EXTRA_IMAGE_LOCAL_PATH);
                    if (item.direct() == EMMessage.Direct.SEND) {
                        File file = new File(localPath);
                        if (file.exists()) {
                            GlideUtils.loadChatImage(mContext, localPath, helper.getView(R.id.bivPic));
                        } else {
                            GlideUtils.loadChatImage(mContext, path, helper.getView(R.id.bivPic));
                        }
                    } else {
                        GlideUtils.loadChatImage(mContext, path, helper.getView(R.id.bivPic));
                    }
                    helper.getView(R.id.bivPic).setOnLongClickListener(view -> {
                        if (messageListener != null) {
                            messageListener.onMsgLongClick(item, helper.getView(R.id.bivPic), helper.getAdapterPosition());
                        }
                        return true;
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)) { // 自定义视频消息
                try {
                    String path = item.getStringAttribute(ChatConstant.EXTRA_IMAGE_PATH);
                    helper.getView(R.id.iv_video).setVisibility(View.VISIBLE);
                    GlideUtils.loadChatImage(mContext, path, helper.getView(R.id.bivPic));
                    helper.getView(R.id.bivPic).setOnLongClickListener(view -> {
                        if (messageListener != null) {
                            messageListener.onMsgLongClick(item, helper.getView(R.id.bivPic), helper.getAdapterPosition());
                        }
                        return true;
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        // 设置各种点击事件
        if (helper.getView(R.id.rl_item_msg_bg) != null) {
            helper.getView(R.id.rl_item_msg_bg).setOnLongClickListener(view -> {
                if (messageListener != null) {
                    messageListener.onMsgLongClick(item, helper.getView(R.id.rl_item_msg_bg), helper.getAdapterPosition());
                }
                return true;
            });
        }

        // 头像点击
        if (helper.getView(R.id.iv_head) != null) {
            helper.getView(R.id.iv_head).setOnClickListener(view -> {
                if (isSelectMore) {
                    return;
                }
                if (messageListener == null) {
                    return;
                }
                try {
                    int userId;
                    boolean isMine;
                    if (item.direct() == EMMessage.Direct.SEND) {
                        isMine = true;
                        userId = item.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
                    } else {
                        isMine = false;
                        userId = item.getIntAttribute(ChatConstant.EXTRA_SEND_USER_ID);
                    }
                    messageListener.onUserHeadClick(userId, isMine);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        // 图片点击
        if (helper.getView(R.id.bivPic) != null) {
            if (messageListener == null) {
                return;
            }
            try {
                helper.getView(R.id.bivPic).setOnClickListener(view -> {
                    if (isSelectMore) {
                        return;
                    }
                    if (messageListener != null) {
                        if (item.getType() == EMMessage.Type.IMAGE) {
                            messageListener.onImageOnClick(item, helper.getView(R.id.bivPic));
                        } else {
                            messageListener.onImageCustomOnClick(item, helper.getView(R.id.bivPic));
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 分享名片点击
        if (helper.getView(R.id.cons_share_user) != null) {
            if (messageListener == null) {
                return;
            }
            try {
                helper.getView(R.id.cons_share_user).setOnClickListener(view -> {
                    if (isSelectMore) {
                        return;
                    }
                    if (messageListener != null) {
                        try {
                            messageListener.shareUserOnClick(item, item.getIntAttribute(ChatConstant.EXTRA_SHARE_USERID));
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 地图点击
        if (helper.getView(R.id.ll_map_view) != null) {
            if (messageListener == null) {
                return;
            }
            try {
                helper.getView(R.id.ll_map_view).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (isSelectMore) {
                            return;
                        }
                        double lat, lng;
                        EMLocationMessageBody body = (EMLocationMessageBody) item.getBody();
                        lat = body.getLatitude();
                        lng = body.getLongitude();
                        messageListener.locationOnClick(item, lat, lng);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void play(EMMessage message, ImageView ivVoice) {
        String localPath = ((EMVoiceMessageBody) message.getBody()).getLocalUrl();
        File file = new File(localPath);
        if (file.exists() && file.isFile()) {
//            ackMessage(message);
            playVoice(message, ivVoice);
            // Start the voice play animation.
            startVoicePlayAnimation(message, ivVoice);
        } else {
            EMLog.e(TAG, "file not exist");
        }
    }

    private void playVoice(EMMessage msg, ImageView ivVoice) {
        voicePlayer.play(msg, mp -> {
            // Stop the voice play animation.
            stopVoicePlayAnimation(msg, ivVoice);
        });
    }

    public void startVoicePlayAnimation(EMMessage message, ImageView ivVoice) {
        if (message.direct() == EMMessage.Direct.RECEIVE) {
            ivVoice.setImageResource(R.drawable.voice_from_icon);
        } else {
            ivVoice.setImageResource(R.drawable.voice_to_icon);
        }
        voiceAnimation = (AnimationDrawable) ivVoice.getDrawable();
        voiceAnimation.start();

        // Hide the voice item not listened status view.
//        if (message.direct() == EMMessage.Direct.RECEIVE) {
//            readStatusView.setVisibility(View.INVISIBLE);
//        }
    }

    public void stopVoicePlayAnimation(EMMessage message, ImageView ivVoice) {
        if (voiceAnimation != null) {
            voiceAnimation.stop();
        }

        if (message.direct() == EMMessage.Direct.RECEIVE) {
            ivVoice.setImageResource(R.mipmap.ic_icon_chat_receive_voice_3);
        } else {
            ivVoice.setImageResource(R.mipmap.ic_icon_chat_send_voice_3);
        }
    }

    /**
     * 消息列表时间监听
     *
     * @param messageListener
     */
    public void setOnChatMessageListener(OnChatMessageListener messageListener) {
        this.messageListener = messageListener;
    }

    public void setHxUserInfoBean(HxUserInfoBean hxUserInfoBean) {
        this.hxUserInfoBean = hxUserInfoBean;
        notifyDataSetChanged();
    }

    /**
     * 设置是否是选择更多模式
     *
     * @param isSelectMore
     */
    public void setIsSelectMore(boolean isSelectMore) {
        this.isSelectMore = isSelectMore;
        notifyDataSetChanged();
    }

    /**
     * 设置选中的列表
     */
    public void setCheckBoxList(List<Integer> list) {
        this.checkBoxList = list;
        notifyDataSetChanged();
    }


    private String getExtMsg(EMMessage message) {
        try {
            boolean to_all = message.getBooleanAttribute("to_all");
//                boolean to_all = item.getBooleanAttribute("to_all");

            String msg_text = message.getStringAttribute("msg_text");
            Log.i("message", "to_all:  YES");
            if (to_all) {
                return msg_text == null ? "" : msg_text;
            } else {
                JSONArray to_memeber = message.getJSONArrayAttribute("to_memeber");
                String hxUserID = UserInfoUtil.getUserXHId();
                for (int i = 0; i < to_memeber.length(); i++) {
                    String mem = to_memeber.getString(i);
                    if (mem.equals(hxUserID)) {
                        return msg_text;
                    }
                }
               return "";
            }
        } catch (Exception e) {
            return null;
        }
    }

}
